package com.bw.module_motorcircle.ui.post

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.RecycledViewPool
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bw.lib_common.base.BaseFragment
import com.bw.lib_common.base.state.RequestEvent
import com.bw.lib_common.livedata_eventbus.Events
import com.bw.lib_common.livedata_eventbuss.LiveEventBus
import com.bw.lib_common.uiLoader.UILoader
import com.bw.lib_common.uiLoader.UIState
import com.bw.lib_common.utils.ToastUtils
import com.bw.lib_storage.UserMMKV
import com.bw.module_motorcircle.R
import com.bw.module_motorcircle.databinding.FragmentPostListBinding
import com.bw.module_motorcircle.databinding.LayoutItemPostListBinding
import com.bw.module_motorcircle.helper.VideoRecyclerViewHelper
import com.bw.module_motorcircle.ui.post.adapter.PostListAdapter
import com.bw.module_motorcircle.ui.post.adapter.PostViewHolder
import com.google.android.exoplayer2.util.MimeTypes
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class PostListFragment : BaseFragment<PostListViewModel,FragmentPostListBinding>() {
    private val mViewModel: PostListViewModel by viewModels()
    override val mLayoutResId: Int
        get() = R.layout.fragment_post_list
    private lateinit var mUiLoader:UILoader

    //分页参数
    private var ifFocus: Int? = null
    private var keyword: String? = null
    private var memberId: String? = null
    private var topicId: String? = null
    private var sortBy: String? = null

    companion object {
        private const val KEYWORD = "keyword"
        private const val SORT_BY = "sort_by"
        private const val MEMBER_ID = "member_id"
        private const val IF_FOCUS = "IF_FOCUS"
        private const val TOPIC_ID = "topic_id"
        fun newInstance(
            ifFocus: Int? = null,
            keyword: String? = null,
            memberId: String? = null,
            topicId: String? = null,
            sortBy: String? = null
        ): PostListFragment {
            val postListFragment = PostListFragment()
            postListFragment.arguments = Bundle().apply {
                putInt(IF_FOCUS, ifFocus ?: 0)
                putString(KEYWORD, keyword)
                putString(MEMBER_ID, memberId)
                putString(TOPIC_ID, topicId)
                putString(SORT_BY, sortBy)
            }
            return postListFragment
        }
    }
    //视频播放帮助类
    private val mVideoRecyclerViewHelper by lazy{
        object :VideoRecyclerViewHelper(){
            override fun getVideoUrl(position: Int): String? {
                return mPostListAdapter.getPostItem(position)?.image?.firstOrNull()?.url
            }

            override fun getVideoContainer(viewHolder: RecyclerView.ViewHolder): FrameLayout? {
                if (viewHolder !is PostViewHolder) {
                    return null
                }
                return viewHolder.mBinding.lVideo
            }

            override fun getVideoCoverView(viewHolder: RecyclerView.ViewHolder): ImageView? {
                if (viewHolder !is PostViewHolder) {
                    return null
                }
                return viewHolder.mBinding.ivVideo
            }

            override fun getVideoIcon(viewHolder: RecyclerView.ViewHolder): View? {
                if (viewHolder !is PostViewHolder) {
                    return null
                }
                return viewHolder.mBinding.ivPlay
            }

            override fun getVideoLoadingView(viewHolder: RecyclerView.ViewHolder): View? {
                if (viewHolder !is PostViewHolder) {
                    return null
                }
                return viewHolder.mBinding.loading
            }

            override fun isVideo(position: Int): Boolean {
                return MimeTypes.isVideo(mPostListAdapter.getPostItem(position)?.image?.firstOrNull()?.contentType)
            }

        }
    }
    private val mPostListAdapter by lazy{
        PostListAdapter(
            onTopicClick = {
                ToastUtils.showLong(requireContext(),"点击了话题跳转到对应页面"+it.topicName)
            },
            onMoreActionClick = {item,position->
                ToastUtils.showLong(requireContext(),"点击了更多"+position)
            },
            onLikeClick = {item,position->
                ToastUtils.showLong(requireContext(),"点击了点赞"+position)
            },
            onImageClick = {item,position->
                ToastUtils.showLong(requireContext(),"点击了图片"+position)
            },
            onPreLoad = {
                //提前加载下一页数据
                mViewModel.pageNum ++
                getPostListData()
                type = 1 //追加数据
            },
            preloadItemCount = 2
        )
    }

    override fun initView() {
        super.initView()
        ifFocus = arguments?.getInt(IF_FOCUS)
        keyword = arguments?.getString(KEYWORD)
        memberId = arguments?.getString(MEMBER_ID)
        topicId = arguments?.getString(TOPIC_ID)
        sortBy = arguments?.getString(SORT_BY)
        initAdapter()
        initUILoader()
        initVideo()
    }

    private fun initVideo() {
        //视频帮助类
        mVideoRecyclerViewHelper.init(
            requireActivity(), mBinding.rv,
            onPlayingVideoClick = null,
            onNotPlayingVideoClick = null
        )
    }
    /**
     * 暂停播放
     */
    override fun onPause() {
        super.onPause()
        mVideoRecyclerViewHelper.pausePlayer()
    }

    /**
     * 恢复播放
     */
    override fun onResume() {
        super.onResume()
        if (isVisible)
            mVideoRecyclerViewHelper.startPlayer()
        else
            mVideoRecyclerViewHelper.hidePlayerView()
    }
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            mVideoRecyclerViewHelper.startPlayer()
        } else {
            mVideoRecyclerViewHelper.pausePlayer()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mVideoRecyclerViewHelper.releasePlayer()
    }

    fun initUILoader(){
        mUiLoader = object : UILoader(requireContext()){
            override fun loadSuccessView(container: ViewGroup?): View? {
                return View(requireContext())
            }
        }
        mBinding.lContainer.addView(mUiLoader)

        mUiLoader.onLoginClick = {
            ARouter.getInstance().build(Router.Ui.LoginActivity).navigation()
        }

    }

    override fun initData() {
        super.initData()
        if (ifFocus == 1){
            //是否登录
            if (UserMMKV.token.isNullOrEmpty()){
                mUiLoader.updateState(UIState.UN_LOGIN)
            }else{
                mViewModel.checkIfHasFocus() //是否有关注的人
            }
        }else{
            //直接加载帖子数据
            getPostListData()
        }
    }
    fun getPostListData(){
        //设置参数
        mViewModel.setPageParam(sortBy, topicId,memberId,ifFocus,topicId)
        //网络请求数据
        mViewModel.pageList()
        //订阅数据，防止一直转圈
        observePostList()
    }
    private var type:Int = 0 // 1:加载更多 2：刷新

    fun observePostList(){
        //订阅帖子数据
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.mPostState.collect{
                    when(it){
                        is RequestEvent.Loading -> {
                            mUiLoader.updateState(UIState.LOADING)

                        }
                        is RequestEvent.Success -> {
                            mUiLoader.updateState(UIState.SUCCESS)
                            //数据更新UI
                            if (type == 0){
                                mPostListAdapter.setData(mViewModel.mPostListData)
                            }else if (type == 1){
                                mPostListAdapter.addData(mViewModel.mPostListData)
                                mBinding.lRefresh.finishLoadMore()
                            }else if (type == 2){
                                mPostListAdapter.setData(mViewModel.mPostListData)
                                mBinding.lRefresh.finishRefresh()

                            }

                        }
                        is RequestEvent.Error -> {
                            mUiLoader.updateState(UIState.NETWORK_ERROR)

                        }
                        is RequestEvent.Empty -> {
                            if (type == 0){
                                mUiLoader.updateState(UIState.EMPTY)
                            }
                        }
                        else -> {}
                    }
                }
            }
        }
    }

    override fun initListener() {
        super.initListener()

        //订阅是否有关注的人
        mViewModel.mCheckIfHasFocus.observe(this){
            if (it == true){
                //直接加载帖子数据
                getPostListData()
            }else{
                mUiLoader.updateState(UIState.NO_FOLLOW)
            }
        }
        //订阅登录成功事件
        LiveEventBus.with<Boolean>(Events.EVENT_LOGIN_SUCCESS).observe(this){
            initData() //重新请求数据，带登录状态
        }
        //上拉下拉
        mBinding.lRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(p0: RefreshLayout) {
                mViewModel.pageNum = 1
                getPostListData()
                type = 2
            }

            override fun onLoadMore(p0: RefreshLayout) {
                mViewModel.pageNum ++
                getPostListData()
                type = 1
            }
        })
    }

    private fun initAdapter() {
        mBinding.rv.adapter = mPostListAdapter
        mBinding.rv.layoutManager = LinearLayoutManager(requireContext())
        mBinding.rv.setHasFixedSize(true)
        mBinding.rv.setItemViewCacheSize(10)
        val pool = RecycledViewPool()
        pool.setMaxRecycledViews(0,10)
        mBinding.rv.setRecycledViewPool(pool)

    }


}